/*
 * Copyright (c) IAR Systems 2021.
 *
 * This file is not a part of Pico SDK.
 *
 * SPDX-License-Identifier: BSD-3-Clause
 */

#if defined (__IAR_SYSTEMS_ICC__)

#include <DLib_Threads.h>
#include "pico/mutex.h"

static mutex_t iar_system_lock[_MAX_LOCK];

 /* Initialize a system lock */
void __iar_system_Mtxinit(__iar_Rmtx *mutex) {
  for (uint32_t index = 0; index < _MAX_LOCK; index++) {
    if (0 == iar_system_lock[index].core.spin_lock) {
      mutex_init(&iar_system_lock[index]);
      *mutex = (__iar_Rmtx)&iar_system_lock[index];
      return;
    }
  }
}

/* Lock a system lock */
void __iar_system_Mtxlock(__iar_Rmtx *mutex) {
  mutex_enter_blocking((mutex_t *)*mutex);
}

/* Unlock a system lock */
void __iar_system_Mtxunlock(__iar_Rmtx *mutex) {
  mutex_exit((mutex_t *)*mutex);
}

/* Destroy a system lock */
void __iar_system_Mtxdst(__iar_Rmtx *mutex) {
  /* For now there is no need to destroy the mutexes */
}

#endif
